﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wedo.Recognition.Domain.Models;
using Wedo.Recognition.Service;
using Wedo.Recognition.Domain;
using System.Web.Mvc;
using Wedo.Service.Common;
using Wedo.Utility;
using Wedo.Mvc.Utility;
using Wedo.Mvc.Pager;
using System.Web.Script.Serialization;
using Wedo.Mvc.Utility.Common;  
using Wedo.Recognition.Service.BankImport;
using Wedo.Utility.ExportFile;
using Wedo.Recognition.Service.Service;
using Wedo.Domain.Models; 
using Wedo.Recognition.Repository;
using Wedo.Recognition.Service.Action;
namespace Wedo.Recognition.Web.Controllers
{
    public class BankDataController : EntityController<BankData, BankDataSearch>
    {
        #region 基础
        private BankDataService service;
        public BankDataController(IUnitWork dbContext)
            : base(dbContext)
        {

            service = new BankDataService(_dbContext);
        }

        protected override IBaseService<BankData> EntityService
        {
            get { return service; }
        }

         #endregion
        #region 查询

        public override ActionResult Search(BankDataSearch where)
        {
            return base.Search(where ?? new BankDataSearch());
        }

        /// <summary>
        /// 销售助理
        /// </summary>
        /// <returns></returns>
        public ActionResult CSRIndex()
        {
            var list = GetSearchPagedList(new BankDataSearch { StartTime = DateTime.Today });
            return ReturnAjaxView("Index", list);
        }

        /// <summary>
        /// 财务账单管理
        /// </summary>
        /// <returns></returns>
        public ActionResult BankDataManage()
        {
            var list = GetSearchPagedList(new BankDataSearch { StartTime = DateTime.Today });
            return ReturnAjaxView(list);
        }

        /// <summary>
        /// 财务签出账单
        /// </summary>
        /// <returns></returns>
        public ActionResult FinanceBankData()
        {
            var list = GetSearchPagedList(new BankDataSearch {  FinanceCheckOut=true });
            return ReturnAjaxView("BankDataManage", list);
        }

        /// <summary>
        /// 锁定的账单
        /// </summary>
        /// <returns></returns>
        public ActionResult CMPIndex()
        {
            ViewData["isShortSearch"] = true;
            var list = GetSearchPagedList(new BankDataSearch { Status = 2, AdvancedSearch = true });
            return ReturnAjaxView("Index", list);
        }

        /// <summary>
        /// 导入的账单
        /// </summary>
        /// <returns></returns>
        public ActionResult IPIndex()
        {
            var list = GetReportQuery(new BankDataReportSearch());
            return ReturnAjaxView("Report", list);
        }


        /// <summary>
        /// 签出的账单
        /// </summary>
        /// <returns></returns>
        public ActionResult MyCheckBankData()
        {
            return CheckSearch(new CommonSearchModel { ApplyMan = CurrentUserName });
        }

        public ActionResult CheckSearch(CommonSearchModel where)
        {
            ViewData["SearchModel"] = where;
            var list = service.CheckSearch(where);
            return ReturnAjaxView(list);
        }

        /// <summary>
        /// 待处理争议账单
        /// </summary>
        public ActionResult DisputeBankData()
        {
            return DisputeBankDataList(new CommonTimeSearch());
        }

        /// <summary>
        /// 待处理争议账单
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public ActionResult DisputeBankDataList(CommonTimeSearch where)
        {
            where = where ?? new CommonTimeSearch();
            IQueryable<BankData> query = service
                .GetAll(m => m.DisputeApply.Count(s => s.Status == 1) > 0);
            if (where.StartTime != null)
            {
                DateTime Start = where.StartTime.Value;
                query = query.Where(m => m.AccountDate > Start);
            }

            if (where.EndTime != null)
            {
                DateTime endTime = where.EndTime.Value.AddDays(1);
                query = query.Where(m => m.AccountDate < endTime);
            }

            if (where.Keyword.IsNotNullOrWhiteSpace())
            {
                query = query.Where(m => m.Assiginment.Contains(where.Keyword));
            }

            var list = query.OrderBy(m => m.Status).ThenByDescending(m => m.Created).ToPagedList(where.Page, 10);
            return ReturnAjaxView(list);
        }


        protected override PagedList<BankData> GetSearchPagedList(BankDataSearch where)
        {

            ViewData["SearchModel"] = where;
            //SetUserInfo();

            return service.GetSearchPagedList(where);
        }

        #endregion
        /// <summary>
        /// 审批争议
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult ApproveDispute(Guid id)
        {
            var model = FindById(id);
            return ReturnAjaxView(model);
        }

        #region 报表

        /// <summary>
        /// 未签出清单
        /// </summary>
        /// <returns></returns>
        public ActionResult UnRecognition()
        {
            ViewData["IsExport"] = true;

            var list = GetReportQuery(new BankDataReportSearch { IsRecognition = false});
            return ReturnAjaxView("Report", list);
        }

        /// <summary>
        /// 入款清单
        /// </summary>
        /// <returns></returns>
        public ActionResult Recieved()
        {
            var list = GetReportQuery(new BankDataReportSearch { IsInSap = true});
            return ReturnAjaxView("Report", list);
        }

        /// <summary>
        /// 争议清单
        /// </summary>
        /// <returns></returns>
        public ActionResult Disputed()
        {
            var list = GetReportQuery(new BankDataReportSearch { IsDisputed = true });

            return ReturnAjaxView("Report", list);
        }

        public ActionResult ReportList(BankDataReportSearch searchModel)
        {
            var list = GetReportQuery(searchModel);
            return ReturnAjaxView(list);
        }

        public ActionResult ReportToDownload(BankDataReportSearch searchModel)
        {
            string name = DateTime.Now.ToString("yyyyMMddHHmmss") + "Bankdata.csv";
            var path = FileHelpers.GetRecivePath("RecieveVoucher", name);
            var list = service.GetReportQuery(searchModel)
                .OrderByDescending(m => m.AccountDate).ToList();

            List<Bank> Banks = _dbContext.Set<Bank>().All().ToList();
            Dictionary<string, string> BankCodeNames = new Dictionary<string, string>();
            foreach (var item in Banks)
            {
                BankCodeNames[item.BankCode] = item.BankName;
            }

            var csv = new BankDataExport(path, list);
            csv.BankNames = BankCodeNames;
            csv.Export();
            return File(path, "application/octet-stream", name);
        }

        private PagedList<BankData> GetReportQuery(BankDataReportSearch where)
        {
            ViewData["SearchModel"] = where;
            return service.GetReportQuery(where).OrderByDescending(m => m.AccountDate).ToPagedList(where.Page, 10);

        }
        #endregion

        #region 操作

        /// <summary>
        /// 修改Document
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult UpdateDocumentNO(Guid id)
        {
            var model = FindById(id);
            return ReturnAjaxView(model);
        }

        [HttpPost]
        public ActionResult UpdateDocumentNO(Guid id, string newDocumentNO)
        {
            try
            {
                service.UpdateDocumentNO(id, newDocumentNO);
                return SuccessMsg("修改Document成功！");
            }
            catch (Exception ex)
            {
                return ErrorMSG(ex.Message);
            }

        }

        public ActionResult FinanceCheckOut(string ids)
        {
            ViewData["ids"] = ids;
            return ReturnAjaxView();
        }

        /// <summary>
        /// 批量财务签出
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult FinanceCheckOut(string ids, string CustomerName, string CustomerCode)
        {
            try
            {
                List<Guid> _ids = ids.ParseToList<Guid>();
                service.FinanceCheck(_ids, CurrentUserName, CustomerName, CustomerCode);
                return SuccessMsg("财务签出成功！");
            }
            catch (Exception ex)
            {
                return ErrorMSG(ex.Message);
            }
        }

        [HttpPost]
        public ActionResult CheckIn(Guid id)
        {
            try
            {
                service.CheckIn(id, CurrentUserName);
                return SuccessMsg("签出成功！");
            }
            catch (Exception e)
            {
                return ErrorMSG(e.Message);
            }
        }

        protected override void DeleteModel(Guid id)
        {
            service.Remove(id);
        }

        /// <summary>
        /// 恢复被废除的账单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RestoreRemove(Guid id)
        {
            try
            {
                service.RestoreRemove(id);
                return SuccessMsg("恢复成功！");
            }
            catch (Exception ex)
            {
                return ErrorMSG(ex.Message);
            }
        }


        #endregion

        #region 上传并处理账单文件

        public ActionResult ImportData()
        {
            return ReturnAjaxView();
        }

        [HttpPost]
        public ActionResult ImportData(ImportType? ImportType)
        {
            if (ImportType == null)
            {
                ViewData["ErrorMSG"] = "请选择上传文件类型！";
                return ReturnAjaxView();
            }

            if (Request.Files.Count == 0)
            {
                ViewData["ErrorMSG"] = "请至少选择一个文件！";
                return ReturnAjaxView();
            }
            else
            {
                try
                {
                    var file = FileHelpers.SaveFile(Request.Files[0], Prefix: DateTime.Now.ToString("yyMMddHHmmss"));
                    var list = service.GetImportBankData(file, ImportType.Value);
                    if (list.Count == 0)
                    {
                        ViewData["ErrorMSG"] = "没有数据或者格式错误！";
                    }
                    else
                    {
                        ViewData["Batch"] = list.FirstOrDefault().BatchID;
                    }
                    return ReturnAjaxView(list);
                }
                catch (Exception ex)
                {
                    ViewData["ErrorMSG"] = "格式错误！错误：" + ex.Message;
                    return ReturnAjaxView();
                }
            }  
        }

        [HttpPost]
        public ActionResult DeleteIP(Guid id)
        {
            try
            {

                service.DeleteIP(id);
                return SuccessMsg("删除成功！");
            }
            catch (Exception ex)
            {
                return ErrorMSG("删除错误：" + ex.Message);
            }
        }

        public ActionResult SaveIPBankData(string batch)
        {
            try
            {
                service.SaveIPBankData(batch, CurrentUserName);
                return SuccessMsg("保存成功！");
            }
            catch (Exception e)
            {
                return ErrorMSG("保存失败：" + e.Message);
            }
        }

        public ActionResult CancelIPBankData(string batch)
        {
            try
            {
                service.ClearBatch(batch);
                return SuccessMsg("取消成功！");
            }
            catch (Exception e)
            {
                return ErrorMSG("取消失败：" + e.Message);
            }
        }

        public ActionResult ImportSapResult()
        {
            return ReturnAjaxView();
        }

        [HttpPost]
        public ActionResult ImportSapResult(string FileName)
        {
            int Count = 0;
            string result;
            int sumCount = 0;
            try
            {
                var names = FileName.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (names != null && names.Length > 0)
                {
                    foreach (var item in names)
                    {
                        int count = 0;
                        int sCount = 0;
                        var file = FileHelpers.GetRecivePath("upload", item);
                        service.AnalyticData(file, CurrentUserName, out count, out sCount, out result);
                        Count += count;
                        sumCount += sCount;
                    }
                }

            }
            catch (Exception ex)
            {
                return ErrorMSG("导入错误：" + ex.Message);
            }
            return SuccessMsg(string.Format("导入成功：总共{0}条，修改了{1}条。", sumCount, Count));

        }

        public ActionResult DownloadTemplete()
        {
            string path = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppData", "");
            return File(path, "application/ms-excel");
        }

        /// <summary>
        /// 导入未认款账单
        /// </summary>
        /// <returns></returns>
        public ActionResult ResolveBankData()
        {
            return ReturnAjaxView("ImportSapResult");
        }

        [HttpPost]
        public ActionResult ResolveBankData(string FileName)
        {
            try
            {
                var names = FileName.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                if (names != null && names.Length > 0)
                {
                    foreach (var item in names)
                    {
                        var file = FileHelpers.GetRecivePath("upload", item);
                        service.ResolveBankData(file, CurrentUserName);
                    }
                }
                else
                {
                    return ErrorMSG("没有此文件！");
                }
            }
            catch (Exception ex)
            {
                return ErrorMSG("导入错误：" + ex.Message);
            }
            return SuccessMsg("导入成功！");

        }

        #endregion


        #region 业务处理

        public ActionResult UnLock(Guid id)
        {
            try
            {
                service.UnLock(id, CurrentUserName);
                return SuccessMsg("解锁成功！");
            }
            catch (Exception e)
            {
                return ErrorMSG(e.Message);
            }
        }

        public ActionResult Lock(Guid id)
        {
            try
            {
                service.Lock(id, CurrentUserName);
                return SuccessMsg("锁定成功！");
            }
            catch (Exception e)
            {
                return ErrorMSG(e.Message);
            }
        }

        public ActionResult DealSAP(Guid id)
        {
            return Details(id);
        }

        [HttpPost]
        public JsonResult DealSAP(Guid id, string CustomerCode, string CustomerName)
        {
            try
            {
                service.DealSAP(id, CustomerCode, CustomerName, CurrentUserName);
                return SuccessMsg(Wedo.Recognition.Resources.ErrorMessage.Add_RefundApply_Success);
            }
            catch (Exception ex)
            {
                return ErrorMSG(ex.Message);
            }
        }

        /// <summary>
        /// 撤销签出
        /// </summary>
        /// <param name="id">签出记录编号</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CancelCheckRecord(Guid id)
        {
            try
            {
                service.CancelCheckIn(id, CurrentUserName);
                return SuccessMsg("撤销签出成功");
            }
            catch (Exception ex)
            {
                return ErrorMSG(ex.Message);
            }
        }

        public ActionResult DeleteCheckRecord(Guid id)
        {
            try
            {
                service.DeleteRecord(id);
                return SuccessMsg("删除签出成功");
            }
            catch (Exception ex)
            {
                return ErrorMSG(ex.Message);
            }
        }

        public ActionResult ApplyDispute(Guid id)
        {
            DisputeApply model = new DisputeApply();
            model.BankDataId = id;
            model.BankData = service.GetById(id);
            return ReturnAjaxView(model);
        }

        /// <summary>
        /// 申请争议 
        /// </summary>
        /// <param name="id">签出记录编号</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ApplyDispute(Guid id, string DisputeReason)
        {
            try
            {
                DisputeApplyService daService = new DisputeApplyService(_dbContext);
                daService.ApplyDispute(id, CurrentUserName, DisputeReason);
                return SuccessMsg("申请争议成功");
            }
            catch (Exception ex)
            {
                return ErrorMSG(ex.Message);
            }
        }

        #region 添加单条认款
        public ActionResult AddPayment(Guid BankDataId)
        {
            var bankdata = service.GetById(BankDataId);
            PaymentApply model = new PaymentApply();
            model.BankDataId = BankDataId;
            model.ApplyMan = CurrentUserName;
            model.ApplyTime = DateTime.Now;
            model.Amount = bankdata.Remain();

            CustomerService cservice = new CustomerService();
            var names= cservice.GetDefaultCustomer(bankdata.Payer);
            if (names != null && names.Length == 2)
            {
                model.CustomerCode = names[0];
                model.CustomerName = names[1];
            }
            else
            {
                string customerCode = bankdata.PaymentApplyCustomeCode();

                if (customerCode.IsNotNullOrWhiteSpace())
                {
                    model.CustomerCode = customerCode;
                    model.CustomerName = bankdata.PaymentApplyCustomeName();
                }
                else
                {
                    if (bankdata.FinanceCheckOut)
                        ViewData["CodeIsNotConfirm"] = true;
                    model.CustomerCode = bankdata.CustomerCode;
                    model.CustomerName = bankdata.CustomerName;
                }
            }

            UserService uService = new UserService(_dbContext);
            var list = uService.GetUserByRole("2").
                Select(m => new SelectListItem { Text = "是（" + m.StaffNameEN + " 审批）", Value = m.Name }).ToList();//财务
            list.Insert(0, new SelectListItem { Text = "否", Value = "" });
            ViewBag.ReleaseOrder = list;//财务

            model.BankData = bankdata;
            return ReturnAjaxView(model);
        }

        [HttpPost]
        public JsonResult AddPayment(PaymentApply model, string FileName)
        {
            List<string> files = FileName
                .Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            List<PaymentAttach> attList = null;
            if (files != null && files.Count > 0)
            {
                attList = new List<PaymentAttach>();
                files.ForEach(s =>
                {
                    string fullName = System.IO.Path.Combine("upload", s);
                    string name = s.Substring(s.IndexOf('_') + 1);
                    attList.Add(new PaymentAttach { FilePath = fullName, FileName = name, ModifiedBy = CurrentUserName, CreatedBy = CurrentUserName });
                });
            }
            try
            {
                model.ApplyTime = DateTime.Now;
                PaymentService pservice = new PaymentService(_dbContext);
                pservice.AddPayment(model, attList);
                return SuccessMsg(Wedo.Recognition.Resources.ErrorMessage.Add_Recognition_Success);
            }
            catch (Exception ex)
            {
                return ErrorMSG(ex.Message);
            }
        }


        [HttpPost]
        public string UploadFile(FormCollection collection)
        {
            if (Request.Files.Count == 0 || Request.Files[0].FileName.IsNullOrWhiteSpace())
            {
                return new ResultMSG("请选择一个文件").ToJson();
            }
            else
            {
                try
                {
                    var file = FileHelpers.SaveFile(Request.Files[0], Prefix: DateTime.Now.ToString("yyMMddHHmmss"));
                    string name = System.IO.Path.GetFileName(file);
                    return new ResultMSG(name, true).ToJson();
                }
                catch (Exception ex)
                {
                    return new ResultMSG(ex.Message).ToJson();
                }
            }
        }

        #endregion

        #region 添加退款申请
        public ActionResult AddRefundment(Guid id)
        {
            var bankdata = service.GetById(id);

            RefundmentApply model = new RefundmentApply();

            model.ApplyMan = CurrentUserName;
            model.ApplyTime = DateTime.Now;
            string customerCode = bankdata.PaymentApplyCustomeCode();
            if (customerCode.IsNotNullOrWhiteSpace())
            {
                model.CustomerCode = customerCode;
                model.CustomerName = bankdata.PaymentApplyCustomeName();
            }
            else
            {
                if(bankdata.FinanceCheckOut)
                    ViewData["CodeIsNotConfirm"] = true;
                model.CustomerCode = bankdata.CustomerCode;
                model.CustomerName = bankdata.CustomerName;
            }

            model.BankDataId = id;
            model.Amount = bankdata.RemainRefundment();

            model.BankData = bankdata;
            return ReturnAjaxView(model);
        }

        [HttpPost]
        public JsonResult AddRefundment(RefundmentApply model)
        {
            try
            {
                RefundmentApplyService raService = new RefundmentApplyService(_dbContext);
                raService.AddRefundment(User.Identity.Name, model);
                return SuccessMsg(Wedo.Recognition.Resources.ErrorMessage.Add_RefundApply_Success);
            }
            catch (Exception ex)
            {
                return ErrorMSG(ex.Message);
            }
        }
        #endregion

        #endregion
    }
}
 